package middleware

import (
	"github.com/duke-git/lancet/v2/convertor"
	"github.com/duke-git/lancet/v2/slice"
	"github.com/gin-gonic/gin"
	"kf/models/dao"
)

type Rbac struct {
	SysRoleDao     *dao.SysRoleDao
	SysRoleMenuDao *dao.SysRoleMenuDao
}

func (rbac *Rbac) RbacAuth1(perm string) gin.HandlerFunc {
	return func(c *gin.Context) {
		roleIdStr, _ := c.Get("role_id")
		roleId, err := convertor.ToInt(roleIdStr)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 403,
				"msg":  "没有权限:" + perm,
			})
			c.Abort()
			return
		}
		role, err := rbac.SysRoleDao.GetRoleForm(roleId)
		if err != nil {
			c.JSON(200, gin.H{
				"code": 403,
				"msg":  "没有权限:" + perm,
			})
			c.Abort()
			return
		}
		var flag bool

		permList := rbac.SysRoleMenuDao.GetRolePermsList(role.Code)
		for _, permBo := range permList {
			perms := permBo.Perms
			flag = slice.Contain(perms, perm)
			if flag {
				break
			}
		}
		if !flag {
			c.JSON(200, gin.H{
				"code": 403,
				"msg":  "没有权限:" + perm,
			})
			c.Abort()
			return
		}
		return
	}
}

func (rbac *Rbac) RbacAuth(c *gin.Context) {
	return
}
